#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // 要导出的类，此类供js调用
    m_myTestClass = new MyTestClass(this);

    // 创建QWebChannel，把创建的类注册到QWebChannel中，js才能调用此类的方法
    m_webChannel = new QWebChannel(this);
    m_webChannel->registerObject("mytestclass", m_myTestClass);


    /*
    // js与C++通信方式一、使用QWebEngineView加载网页，web端js与C++之间的通信
    QString strHtml = QApplication::applicationDirPath() + "/../../testWeb/test.html";
    // QWebEngineView 基于 Chromium 的 web 引擎
    m_webEngineView = new QWebEngineView(this);
    m_webEngineView->load(QUrl::fromLocalFile(strHtml));
    m_webEngineView->page()->setWebChannel(m_webChannel);
    ui->verticalLayout->addWidget(m_webEngineView);
    */


    // js与C++通信方式二、创建QWebsocketServer，web端与之建立连接
    startServer();

}

MainWindow::~MainWindow()
{
    delete ui;
}


// 建立WebSocket服务
void MainWindow::startServer()
{
    m_websocketServer = new QWebSocketServer("testWebchannel", QWebSocketServer::NonSecureMode, this);

    if(!m_websocketServer->listen(QHostAddress::Any, 12345))
    {
        qDebug() << "websocket server listen failed, error: " << m_websocketServer->errorString();
        return;
    }

    connect(m_websocketServer, &QWebSocketServer::newConnection, this, &MainWindow::onNewConnection);
    qDebug() << "startServer";
}

void MainWindow::onNewConnection()
{
    QWebSocket* client = m_websocketServer->nextPendingConnection();
    qDebug() << (QString("Homay robot server has new connection from %1.%2").arg(client->peerAddress().toString()).arg(client->localPort()));

    auto pTransport = new WebSocketTransport(client);
    // 可以不需要，这里只是为了调试打印js端的qwebchannel.js是怎么和C++端通信的，通信协议是什么样的
    connect(pTransport, &WebSocketTransport::messageReceived, this, &MainWindow::onTransportMessageReceived);

    m_webChannel->connectTo(pTransport);
}

void MainWindow::onTransportMessageReceived(const QJsonObject &message, QWebChannelAbstractTransport *transport)
{
    qDebug() << "onTransportMessageReceived: " << message;
}
